package com.cxy.datawarehouse.biz;

import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.cxy.datawarehouse.entity.User;
import com.cxy.datawarehouse.exception.BizException;
import com.cxy.datawarehouse.service.UserService;
import com.cxy.datawarehouse.utils.PasswordUtils;
import com.cxy.datawarehouse.utils.TokenUtils;
import com.cxy.datawarehouse.voEntity.UserLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@Component
public class UserBiz {
    @Resource
    UserService userService;

    public void create(User user) {
        String username = user.getUserName();
        User e = userService.getUserByUserName(username);
        if (e != null) {
            throw new BizException("用户已存在");
        }

        String phone = user.getPhone();
        if (StrUtil.isNotBlank(phone)) {
            if (!PhoneUtil.isPhone(phone)) {
                throw new BizException("手机号码不正确");
            }
            e = userService.getUserByPhone(phone);
            if (e != null) {
                throw new BizException("手机号已存在");
            }
        }
        //密码加密存储
        String encrypt = PasswordUtils.encrypt(user.getPassword());
        user.setPassword(encrypt);
        userService.create(user);
    }

    public String loginByName(UserLoginVo user) {
        String username = user.getUserName();
        String password = user.getPassword();
        User e = userService.getUserByUserName(username);
        if (e == null) {
            throw new BizException("用户名或者密码不正确");
        }
        String pwd = e.getPassword();
        if (!PasswordUtils.matches(password, pwd)) {
            throw new BizException("用户名或者密码不正确");
        }
        return TokenUtils.setUserToken(e);
    }

    public User getUserInfo(String token) {
        return TokenUtils.getUserSession(token);
    }

    public void logout(String token){
        TokenUtils.deleteUserSession(token);
    }

}
